package com.jinchengll.xigua.ui.base;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

/**
 * @author jinchengll
 * @since 2021/10/3
 */
public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        setCustomDensity(this, getApplication());
        initView();
        initData();
    }


    /**
     * 获取Layout资源id
     */
    protected abstract int getLayoutId();

    /**
     * 初始化View
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();


    /**
     * 获取ViewModel
     */
    protected <T extends ViewModel> T getViewModel(Class<T> clazz) {
        return new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory())
                .get(clazz);
    }

    private static float sCompatDensity;
    private static float sCompatScaledDensity;

    /**
     * 屏幕适配方案，以宽维度来适配
     */
    private static void setCustomDensity(Activity activity, Application application) {
        DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (sCompatDensity == 0) {
            sCompatDensity = appDisplayMetrics.density;
            sCompatScaledDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sCompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        // 以360dp为宽度的设计稿(这里发生取整，之后需要检查是否引发问题)
        float density = (float) (appDisplayMetrics.widthPixels / 360.0);
        float scaledDensity = density * (sCompatScaledDensity / sCompatDensity);
        int densityDpi = (int) (density * 160);
        appDisplayMetrics.density = density;
        appDisplayMetrics.scaledDensity = scaledDensity;
        appDisplayMetrics.densityDpi = densityDpi;
        // 更改activity
        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = density;
        activityDisplayMetrics.scaledDensity = scaledDensity;
        activityDisplayMetrics.densityDpi = densityDpi;
    }
}
